﻿#include "httprequest.h"

HttpRequest::HttpRequest(const std::string& version):m_version(version)
{}
//  设置头部字段
void HttpRequest::setHeader(const std::string &key, const std::string &value)
{
    m_headers[key] = value;
}
// 设置查询字符串
void HttpRequest::setQuery(const std::string &key, const std::string &value)
{
    m_querys[key] = value;
}
// 设置正文
void HttpRequest::setBody(const std::string &body, const std::string &type)
{
    m_body = body;
    setHeader("Content-Type", type);
}
// 获取正文
std::string HttpRequest::getBody() const
{
    return m_body;
}
// 重置
void HttpRequest::reset()
{   
    m_method.clear();
    m_path.clear();
    m_version = g_defaulthHttpVersion;
    m_headers.clear();
    m_body.clear();
    std::smatch match;
    m_matches.swap(match);
    m_querys.clear();
}
// 判断是否存在指定头部字段
bool HttpRequest::hasHeader(const std::string &key) const
{
    auto it = m_headers.find(key);
    if (it != m_headers.end())
    {
        return true;
    }
    return false;
}
// 判断是否存在查询字符
bool HttpRequest::hasQuery(const std::string &key) const
{
    auto it = m_querys.find(key);
    if (it != m_querys.end())
    {
        return true;
    }
    return false;
}
// 获取指定头部字段
std::string HttpRequest::getHeader(const std::string &key) const
{
    auto it = m_headers.find(key);
    if (it != m_headers.end())
    {
        return it->second;
    }
    return "";
}
// 获取指定查询字符串
std::string HttpRequest::getQuery(const std::string &key) const
{
    auto it = m_querys.find(key);
    if (it != m_querys.end())
    {
        return it->second;
    }
    return "";
}
// 针对某些头部字段的专用函数
size_t HttpRequest::contentLength() const
{
    auto ret = getHeader("Content-Length");
    if (ret.size() != 0)
    {
        return std::stoi(ret);
    }
    return 0;
}
std::string HttpRequest::contentType() const
{
    auto ret = getHeader("Content-Type");
    if (ret.size() != 0)
    {
        return ret;
    }
    return "";
}
// 是不是短连接
bool HttpRequest::close() const
{
    // 没有Connection字段，或者有Connection但是值是close，则都是短链接，否则就是长连接
    if (hasHeader("Connection") == true && getHeader("Connection") == "keep-alive")
    {
        return false;
    }
    return true;
}